import { getInfoArticle, getInfoImage } from '@/api/user';
import { Promise } from 'core-js';
// 获取文章详情数据用于位置发布选择草稿箱
async function articleId(id) {
  let enclosureBOList = [];
  let data;
  await getInfoArticle(id).then(res => {
    data = res.data.data;
    let datas = res.data.data;
    datas.enclosureVOList.forEach(item => {
      enclosureBOList.push({
        documentUrl: item.documentUrl, // 附件地址
        documentFormat: item.documentFormat, // 附件格式
        documentName: item.documentName // 附件名称
      });
    });
  });
  let list = {
    infoBO: {
      id: null,
      infoName: data.infoVO.infoName, // 发布标题
      isDraft: 0, // 是否是草稿0非草稿  1草稿
      infoType: 3, // 1图像  3文章
      thumbnailUrl: data.infoVO.thumbnailUrl, // 展示封面(缩略图url)
      isForever: 0, // 0非永久 1永久
      releaseOpportunityType: null, // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
      validPeriodStart: '', // 有效期开始
      validPeriodStop: '' // 有效期结束
    },
    // 文章信息
    articleBO: {
      id: null,
      articeTitle: data.infoVO.infoName, // 文章标题
      articleContent: data.articleVO.articleContent // 文章内容标签
    },
    positionBOList: [],
    enclosureBOList: enclosureBOList // 附件信息
  };
  return Promise.reject(list);
}
// 获取图像详情数据用于位置发布选择草稿箱
async function infoImageId(infoType, id) {
  let documentVO = [];
  let datas;
  await getInfoImage(id).then(res => {
    datas = res.data.data;
    res.data.data.imageVideoVOList.forEach(item => {
      documentVO.push({
        coverUrl: item.coverUrl,
        fileSize: item.fileSize,
        fileUrl: item.fileUrl,
        type: item.fileUrl.substr(item.fileUrl.length - 1, 1) === '4' ? 1 : 0 // 0 图片 1 视频
      });
    });
  });
  let list = {
    infoBO: {
      thumbnailUrl: datas.infoVO.thumbnailUrl,
      imageVideoBOList: documentVO,
      infoType: infoType,
      isDraft: 0,
      infoName: datas.infoVO.infoName,
      infoDesc: datas.infoVO.infoDesc,
      infoTimeType: datas.infoVO.infoTimeType,
      infoDuration: datas.infoVO.infoDuration
    }
  };
  return Promise.reject(list);
}
// 处理模块类型
function moduleTypes(list, patternState) {
  let data = [];
  list.forEach(item => {
    if (item.id === 13) {
      item.type = 'JPG、JPEG、PNG、 MP4';
    } else {
      item.type = '富文本';
    }
    data.push({ type: item.type });
  });
  let quchongList = quchong(data, 'type');
  let lists = [];
  quchongList.forEach(item => {
    lists.push(item.type);
  });
  let type = lists.join('，');
  return type;
}
function quchong(dataList, id) {
  let res = []; // 去重复后的集合
  let tem = {};
  for (let i = 0; i < dataList.length; i++) {
    if (!tem[dataList[i][id]]) {
      res.push(dataList[i]);
      tem[dataList[i][id]] = 1;
    }
  }
  return res;
}
// 时间戳转hh:mm:ss
const getTimesBySecond = s => {
  let t = '00:00';
  if (s > -1) {
    let hour = Math.floor(s / 3600);
    let min = Math.floor(s / 60) % 60;
    let sec = Math.floor(s % 60);
    t = hour <= 0 ? '' : `${hour < 10 ? `0${hour}` : hour}:`;
    t += `${min < 10 ? `0${min}` : min}:${sec < 10 ? `0${sec}` : sec}`;
  }
  return t;
};
// 设置视频第一帧为封面
function setVideoPoster(video) {
  video.currentTime = 1;
  let canvas = document.createElement('canvas');
  canvas.width = video.width;
  canvas.height = video.height;
  canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
  video.poster = canvas.toDataURL('image/png');
  video.currentTime = 0;
}
// 移除富文本内容里html标签
function removeHtmlTags(html) {
  // 匹配 HTML 标签的正则表达式
  let regex = /(<([^>]+)>)/gi;
  // 使用空字符串替换匹配到的 HTML 标签
  return html?.replace(regex, '').replace(/&nbsp;/gi, '');
}

// 记录上一页路由，解决go(-1)在基座里面无效的问题
function saveFromRouter(to, from) {
  let { path, query } = from;
  // isBack标记返回、发布信息图像文章切换不记录
  let isAddCache =
    !to.query.isBack &&
    !(
      (path === '/post-message/imgAndVideo' && to.path === '/post-message/article') ||
      (path === '/post-message/article' && to.path === '/post-message/imgAndVideo')
    );
  if (isAddCache) {
    let historyRouterList;
    try {
      historyRouterList = JSON.parse(sessionStorage.getItem('historyRouterList')) || [];
    } catch (error) {
      historyRouterList = [];
    }
    let fromRouteObj = {
      path,
      query
    };
    // 回到信息发布、设备列表、历史发布清空缓存
    if (['/service/send', '/service/record', '/service/devices'].includes(to.path)) {
      historyRouterList = [];
    } else {
      historyRouterList.push(fromRouteObj);
    }
    sessionStorage.setItem('historyRouterList', JSON.stringify(historyRouterList));
  }
}
function getFromRouteInfo() {
  let historyRouterList;
  try {
    historyRouterList = JSON.parse(sessionStorage.getItem('historyRouterList'));
  } catch (error) {
    historyRouterList = [];
  }
  let lastIdx = historyRouterList.length - 1;
  let { path, query } = historyRouterList[lastIdx];
  historyRouterList.splice(lastIdx, 1);
  sessionStorage.setItem('historyRouterList', JSON.stringify(historyRouterList));
  return {
    path,
    query: { ...query, isBack: true }
  };
}

/**
 * 节流函数：在一定时间内只执行一次函数
 * @param {Function} fn 需要执行的函数
 * @param {Number} delay 延迟的毫秒数
 * @returns {Function} 节流函数
 */
const throttleFun = (fn, delay) => {
  let timerId;
  return function (...args) {
    if (!timerId) {
      fn.apply(this, args); // 执行传入的函数
      timerId = setTimeout(() => {
        timerId = undefined; // 延迟结束后，重置定时器ID
      }, delay);
    }
  };
};

export {
  articleId,
  infoImageId,
  moduleTypes,
  getTimesBySecond,
  setVideoPoster,
  removeHtmlTags,
  saveFromRouter,
  getFromRouteInfo,
  throttleFun
};
